package com.example.nutritionmate.controller;

import com.example.nutritionmate.entity.User;
import com.example.nutritionmate.service.CalorieService;
import com.example.nutritionmate.service.MealNutritionService;
import com.example.nutritionmate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/calorie")
public class CalorieController {
    @Autowired
    private CalorieService calorieService;

    @Autowired
    private UserService userService;
    @GetMapping("/dayCalories")
    public ResponseEntity<?> getTotalCaloriesByDate(@AuthenticationPrincipal UserDetails userDetails,
                                                    @RequestParam String date) {
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
        User user = optionalUser.get();

        LocalDate localDate;
        try {
            localDate = LocalDate.parse(date);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("日期格式错误，正确格式为 yyyy-MM-dd");
        }

        Double totalCalories = calorieService.getTotalCaloriesByUserByDate(user, localDate);
        if (totalCalories == null) {
            totalCalories = 0.0;
        }
        return ResponseEntity.ok(totalCalories);
    }

    @GetMapping("/weekCalories")
    public ResponseEntity<?> getTotalCaloriesWeekly(@AuthenticationPrincipal UserDetails userDetails,
                                                    @RequestParam String date) {
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
        User user = optionalUser.get();

        LocalDate localDate;
        try {
            localDate = LocalDate.parse(date);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("日期格式错误，正确格式为 yyyy-MM-dd");
        }

        List<Double> calorieWeekly = calorieService.getWeeklyCalories(user, localDate);
        if (calorieWeekly == null) {
            return ResponseEntity.badRequest().body("返回为空");
        }
        return ResponseEntity.ok(calorieWeekly);
    }
}
